<template>
  <div>
    <el-form
      :model="userForm"
      :rules="rules"
      ref="userForm"
    >
      <el-form-item prop="username">
        <el-input
          v-model="userForm.username"
          placeholder="请输入用户名"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item
        prop="credential"
        style="margin-bottom:0;"
      >
        <el-input
          v-model="userForm.credential"
          placeholder="请输入密码"
          type="password"
          show-credential
          @keyup.enter.native="submitForm('userForm')"
        ></el-input>
      </el-form-item>
      <el-form-item class="reset">
        <router-link to="/forgetpassword">
          <span class="forget">
            忘记密码
          </span>
        </router-link>
      </el-form-item>
      <el-form-item>
        <el-button
          class="g-form"
          type="primary"
          :loading="loading"
          @click="submitForm('userForm')"
        >
          登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
export default {
  name: 'LoginForm',
  data () {
    return {
      loading: false,
      tipVisible: true,
      userForm: {
        username: '',
        credential: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名或手机号', trigger: 'blur' }
        ],
        credential: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      }
    }
  },
  methods: {
    ...mapActions({
      login: 'user/login'
    }),
    // 提交表单
    submitForm (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.handleSignIn()
        } else {
          return false
        }
      })
    },
    // 登录
    async handleSignIn () {
      this.loading = true
      try {
        // 密码登录
        await this.login({ userInfo: this.userForm, type: 'password' })
        this.$message.success('登录成功')
        this.loading = false
        // 跳转目标
        const redirect = this.$route.query.redirect
        if (redirect) {
          this.$router.push({ path: redirect })
        } else {
          this.$router.push({ name: 'Home' })
        }
      } catch {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.forget {
  float: right;
}
</style>
